package cn.rui.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.swing.DesktopUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import cn.rui.baidu.map.Bmap4jException;
import cn.rui.baidu.map.Geocoder;
import cn.rui.baidu.map.res.AddressToLocation;
import cn.rui.baidu.map.res.Search;
import de.felixroske.jfxsupport.FXMLController;
import javafx.event.ActionEvent;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;
import java.util.stream.Collectors;

/**
 * @author chenwenxi
 */
@Slf4j
@FXMLController
@RequiredArgsConstructor
public class MainController implements Initializable {
    public TextField txt_maxPageNum;
    public TextField txt_radius;
    public TextField txt_query;
    public TextField txt_place;

    public Button btn_query;
    public TextArea txtArea_logs;

//    private final String excelFolder = "d://百度地图导出Excel";
    private final String excelFolder = "/Users/chenwenxi/男装";

    Geocoder geocoder = new Geocoder("qIvsQOWaRi2Oov6dlVYpeDCAk3mQQqK5", "DP9EUX4uKW5h8U4KTSDyUR3Hr4oZZZWg");

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        txtArea_logs.setWrapText(true);
    }

    public void queryAndSaveExcel(ActionEvent actionEvent) {
        txtArea_logs.appendText(StrUtil.CRLF + "程序开始运行...");
        InputInfo inputInfo = new InputInfo(txt_place.getText(), Convert.toLong(txt_radius.getText()), txt_query.getText(), Convert.toInt(txt_maxPageNum.getText()));
        txtArea_logs.appendText(StrUtil.CRLF + "检测输入:" + inputInfo);
        btn_query.setDisable(true);
        btn_query.setText("程序运行中");

        this.queryAndSaveExcel(inputInfo);


        //        txtArea_logs.setScrollTop(0);
        btn_query.setDisable(false);
        btn_query.setText("查询并保存到本地");
    }

    public void openExcelFolder(ActionEvent actionEvent) {
        txtArea_logs.appendText(StrUtil.format("{}打开导出目录", StrUtil.CRLF));
        this.mkdir();
        DesktopUtil.open(new File(excelFolder));
    }

    @Data
    @AllArgsConstructor
    public static class InputInfo {
        private String place;
        //方圆
        private Long radius;
        private String query;
        private int maxPageNum;

    }

    private void queryAndSaveExcel(InputInfo inputInfo) {
        try {
            AddressToLocation loc = geocoder.addressToLocation(inputInfo.getPlace());
            txtArea_logs.appendText(StrUtil.format("{}地点:{},查询到经纬度为:{}", StrUtil.CRLF, inputInfo.getPlace(), loc.getResult().getLocation()));
            List<Search.ResultsBean> all = new ArrayList<>();
            for (int i = 0; i < inputInfo.getMaxPageNum(); i++) {
                Search search = geocoder.search(loc, inputInfo);
                List<Search.ResultsBean> results = search.getResults();
                all.addAll(results);
                txtArea_logs.appendText(StrUtil.format("{}-------------爬取页数:{},获取到数据量:{}", StrUtil.CRLF,i+1,
                        results.size()));
                if(results.size() == 0){
                    txtArea_logs.appendText(StrUtil.format("{}已经没有下一页了!!!!", StrUtil.CRLF));
                    break;
                }
                results.forEach(res->{
                    txtArea_logs.appendText(StrUtil.format("{}地址:{},号码:{}", StrUtil.CRLF,res.getAddress(),
                            res.getTelephone()));
                });
            }
            this.saveExcel(all);
        } catch (Bmap4jException e) {
            txtArea_logs.appendText("程序异常:" + e.toString());
        }
    }

    @Data
    @AllArgsConstructor
    public static class 男装Info {
        private String phone;
        private String addr;
    }

    private void mkdir(){
        if(!FileUtil.exist(excelFolder)){
            txtArea_logs.appendText(StrUtil.format("{}创建excel导出目录:{}", StrUtil.CRLF,excelFolder));
            FileUtil.mkdir(excelFolder);
        }
    }

    private void saveExcel(List<Search.ResultsBean> all) {
        List<男装Info> collect =
                all.stream().map(s -> new 男装Info(s.getTelephone(), s.getAddress())).collect(Collectors.toList());
        // 通过工具类创建writer
        this.mkdir();
        String file = StrUtil.format("{}/{}.xlsx", excelFolder, DateUtil.format(new Date(), DatePattern.CHINESE_DATE_TIME_FORMAT));
        txtArea_logs.appendText(StrUtil.format("{}数据收集完成,整理为excel", StrUtil.CRLF));
        ExcelWriter writer = ExcelUtil.getWriter(file);
        // 合并单元格后的标题行，使用默认标题样式
        writer.merge(4, "数据导出");
        // 一次性写出内容，使用默认样式，强制输出标题
        writer.write(collect, true);
        // 关闭writer，释放内存
        writer.close();
        txtArea_logs.appendText(StrUtil.format("{}excel导出完成:{}", StrUtil.CRLF, file));
    }
}
